package com.hj.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.hj.reggie.common.BaseContext;
import com.hj.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录 过滤器
 *
 * @author 37460
 * WebFilter 拦截过滤器注解
 * @Slf4j 日志工具注解
 */

@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    /**
     * 过滤地址设置定义不需要处理的路径
     */
    public static final String[] URlS = new String[]{"/employee/login", "/employee/logout", "/backend/**", "/front/**","/common/**"};
    /**
     *  路径匹配器对象
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到请求{}", request.getRequestURI());
        //1获取本次请求的url
        String requestURI = request.getRequestURI();
        //2判断本次请求是否需要处理
        boolean check = check(URlS, requestURI);
        //3如果登录不需要处理，则直接放行
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        //4判断登录状态，如果已经登录，则直接放行
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            Long empId = (Long) request.getSession().getAttribute("employee");
            //往ThreadLocal中插入id
            BaseContext.setCurrentId(empId);
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //5如果未登录则返回登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }


    /**
     * 检查拦截的url是否可以放行
     *
     * @param urls       urls放行得链接数组
     * @param requestUrl 拦截到得url
     * @return 在放行数组中返回true 不在返回false
     */
    public boolean check(String[] urls, String requestUrl) {
        for (String url : urls) {
            //判断拦截路径是否在放行地址中
            if (PATH_MATCHER.match(url, requestUrl)) {
                //在的话返回true
                return true;
            }
        }
        //不在返回false
        return false;
    }
}
